<?php

/**
 * 京东商品信息获取
 * File Name：JdApi.php
 * File Encoding：UTF-8
 * File New Time：2014-6-27 14:15:21
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class JdApi {

    /**
     * 链接淘宝api服务
     * @staticvar null $handier
     * @return \TaoAPI
     */
    static public function getInstance() {
        static $handier = NULL;
        if (empty($handier)) {
            $handier = new JdApi();
        }
        return $handier;
    }

    /**
     * 设置商品id
     * @param type $productId
     * @return \TaobaoApi
     */
    public function productId($productId = 0) {
        $this->productId = $productId;
        return $this;
    }

    /**
     * 获取店铺名称
     * @param type $product_id
     * @return string
     */
    public function getNick($product_id = '') {
        if (empty($product_id)) {
            if (empty($this->productId)) {
                return false;
            } else {
                $product_id = $this->productId;
            }
        }
        $html = $this->getHtml("http://st.3.cn/gvi.html?callback=setPopInfo&type=popdeliver&skuid={$product_id}", array(
            "User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; de-de) AppleWebKit/534.15+ (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4",
            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language: {zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3}",
            'Cookie:JAMCookie=true; abtest=20140627154945495_50; sid=""; JAMCookie=true; USER_FLAG_CHECK=57fceb4b253e90bcaf74bc0cd9b87727; mobilev=wap; warehistory="1108825495,1073368612,"; JSESSIONID=70F0E0374456771FD6519F9EBFD1EE32.s1; __utmmobile=0xe32197f84c2f4a31.1403855395705.1403855395706.1404262674579.2; __mjdv=direct|-|none|-; __mjdb=10',
            'DNT:1',
            'Host:st.3.cn',
            'Pragma:no-cache',
        ));
        if (empty($html)) {
            return '京东商城';
        }
        $json = json_decode(str_replace(array('setPopInfo({', '})'), array('{', '}'), iconv('gb2312', 'utf-8//IGNORE', $html)), true);
        if (empty($json) || !is_array($json)) {
            return '京东商城';
        }
        return $json['vender'];
    }

    /**
     * 根据商品id获取店铺类型
     * @param type $product_id 商品id
     * @return int 1为京东
     */
    public function getShopType($product_id) {
        $item_type = 0;
        if (empty($product_id)) {
            if (empty($this->productId)) {
                return $item_type;
            } else {
                $product_id = $this->productId;
            }
        }
        if ($product_id < 9999999) {
            $item_type = 1;
        }
        return $item_type;
    }

    /**
     * 得到单个商品信息
     * @param type $product_id 商品id
     * @return array|
     */
    public function getItem($product_id = '') {
        if (empty($product_id)) {
            if (empty($this->productId)) {
                return false;
            } else {
                $product_id = $this->productId;
            }
        } else {
            $this->productId = $product_id;
        }
        $cacheKey = md5('jdApi_getItem_' . $product_id);
        $cache = Yii::app()->cache->get($cacheKey);
        if (!empty($cache)) {
            return $cache;
        }
        $shopInfo = array(
            'detail_url' => "http://item.jd.com/{$product_id}.html",
            'product_id' => $product_id,
        );
        $html = $this->getHtml("http://m.360buy.com/product/{$product_id}.html?v=w");
        if (empty($html)) {
            return false;
        }
        //标题
        preg_match('/<title>(.*?)<\/title>/', $html, $title);
        $shopInfo['title'] = str_replace(array('京东手机版', '-', ' '), '', $title[1]);
        //价格获取
        $price = $this->getPrice();
        if (!empty($price)) {
            $shopInfo = array_merge($shopInfo, $price);
        } else {
            //价格
            preg_match('/<font color="red" style="font-family:Arial;font-weight:bold;font-size:18px">&yen;(.*?)<\/font>/', $html, $price);
            $shopInfo['promo_price'] = $price[1];
            $shopInfo['p_price'] = $price[1];
        }
        //图片
        $htmlImg = $this->getHtml("http://m.360buy.com/moreimg/{$product_id}.html?v=w");
        preg_match_all('/<p style="padding-left:5px;"><a href=\'(.*?)\'><img/', $htmlImg, $img);
        $shopInfo['images'] = $img[1];
        //店铺类型
        $shopInfo['item_type'] = $this->getShopType($product_id);
        //买方名称
        $shopInfo['nick'] = $this->getNick();
        //销量
        $shopInfo['sales'] = $this->getSales($product_id);
        Yii::app()->cache->set($cacheKey, $shopInfo, 3000);
        return $shopInfo;
    }

    /**
     * 获取原价和现价
     * @return boolean
     */
    public function getPrice($product_id = '') {
        if (empty($product_id)) {
            if (empty($this->productId)) {
                return false;
            } else {
                $product_id = $this->productId;
            }
        }
        $json = $this->getHtml("http://p.3.cn/prices/get?skuid=J_{$product_id}&type=1&area=1_72_2799");
        if (empty($json)) {
            return array(
                'promo_price' => '',
                'p_price' => '',
            );
        }
        $json = json_decode($json, true);
        if (empty($json) || !is_array($json)) {
            return array(
                'promo_price' => '',
                'p_price' => '',
            );
        }
        return array(
            'promo_price' => $json[0]['p'],
            'p_price' => $json[0]['m'],
        );
    }

    /**
     * 获取商品销量
     * @param type $product_id
     * @return boolean
     */
    public function getSales($product_id = '') {
        if (empty($product_id)) {
            if (empty($this->productId)) {
                return false;
            } else {
                $product_id = $this->productId;
            }
        }
        $html = $this->getHtml("http://club.jd.com/ProductPageService.aspx?method=GetCommentSummaryBySkuId&referenceId={$product_id}&callback=getCommentCount");
        if(empty($html)){
            return false;
        }
        $json = json_decode(str_replace(array('getCommentCount({', '})'), array('{', '}'), $html), true);
        if (empty($json) || !is_array($json)) {
            return false;
        }
        return $json['CommentCount'];
    }

    /**
     * 根据地址抓取淘宝页面html代码
     * @param string $url 地址
     * @param array $httpheader CURLOPT_HTTPHEADER信息
     * @return boolean
     */
    public function getHtml($url, $httpheader = array(
        "User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; de-de) AppleWebKit/534.15+ (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4",
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language: {zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3}",
        'Cookie:aview=1484.1077968113; atw=1484.1077968113.5; __jda=122270672.1764698062.1405073291.1405073291.1405073291.1; __jdb=122270672.1.1764698062|1.1405073291; __jdc=122270672; __jdv=122270672|direct|-|none|-; ipLocation=%u5317%u4EAC; areaId=1; ipLoc-djd=1-72-2799-0; __jdu=1764698062',
        'DNT:1',
        'Host:m.360buy.com',
        'Pragma:no-cache',
    )) {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        // 设置 url
        curl_setopt($ch, CURLOPT_URL, $url);
        //构造IP
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:127.0.0.1', 'CLIENT-IP:127.0.0.0'));
        //构造来路
        curl_setopt($ch, CURLOPT_REFERER, "http://m.360buy.com/");
        // 设置浏览器的特定header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
        // 页面内容我们并不需要
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        // 只需返回HTTP header
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 返回结果，而不是输出它
        //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        ob_start();
        curl_exec($ch);
        $html = ob_get_contents();
        ob_end_clean();
        curl_close($ch);
        return $html;
    }

}
